<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告视图区域 -->
      <!-- 这是一个不可关闭的警告 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <el-row>
        <el-col>
          <span> 选择商品分类: </span>
          <!-- 级联选择区域 -->
          <el-cascader
            v-model="selectedCategoriseKeys"
            :options="categoriesList"
            :props="cascaderProps"
            @change="handleCascaderChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页区域 -->
      <el-tabs v-model="activeTabsName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddAttributesDialog"
            class="btnMargin"
            >添加参数</el-button
          >
          <!-- 表格组件，表格数据从data中获取，每列数据从prop中获取 -->
          <el-table :data="manyTabList" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮区域 -->
                <el-button
                  v-else
                  size="small"
                  class="button-new-tag"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteAttributes(scope.row)"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddAttributesDialog"
            class="btnMargin"
            >添加属性</el-button
          >
          <el-table :data="onlyTabList" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入框区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮区域 -->
                <el-button
                  v-else
                  size="small"
                  class="button-new-tag"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteAttributes(scope.row)"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加 参数 的对话框 -->
    <el-dialog
      :title="'添加' + dialogText"
      :visible.sync="addAttributesVisible"
      width="50%"
      @close="$refs.addAttributesFormRef.resetFields()"
    >
      <el-form
        :model="addAttributesForm"
        :rules="attributesFormRules"
        ref="addAttributesFormRef"
        label-width="100px"
      >
        <el-form-item :label="dialogText + ' :'" prop="attr_name">
          <el-input v-model="addAttributesForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttributesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttributes">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 动态参数 的对话框 -->
    <el-dialog
      :title="'编辑' + dialogText"
      :visible.sync="editAttributesVisible"
      width="50%"
      @close="$refs.editAttributesFormRef.resetFields()"
    >
      <el-form
        :model="editAttributesForm"
        :rules="attributesFormRules"
        ref="editAttributesFormRef"
        label-width="100px"
      >
        <el-form-item :label="dialogText + ' :'" prop="attr_name">
          <el-input v-model="editAttributesForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttributesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAttributes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 级联选择器选中的分类列表
      selectedCategoriseKeys: [],
      // 分类列表
      categoriesList: [],
      // 分类参数列表(动态参数列表)
      manyTabList: [],
      // 分类参数列表(静态属性列表)
      onlyTabList: [],
      //   指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      // 被激活的页签名称
      activeTabsName: 'many',
      // 控制对话框的显示与隐藏
      addAttributesVisible: false,
      editAttributesVisible: false,
      // 验证参数规则
      attributesFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 参数表单对象
      addAttributesForm: {
        attr_name: '',
      },
      editAttributesForm: {},
    }
  },
  methods: {
    // 级联选择框选择项变化，会触发
    handleCascaderChange() {
      // 然后通过获取 activeTabsName 的值来指定参数是 动态参数 或 静态属性
      this.getAttributes()
    },
    // 获取分类的列表数据
    async getCategoriesList() {
      //   get请求携带参数需要params
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('查询分类信息失败')
      }
      //   仔细查看文档和控制台，网络请求返回的是什么样的数据
      this.categoriesList = res.data
    },
    // 处理tabs标签页的变化
    handleTabsClick() {
      // 然后通过获取 activeTabsName 的值来指定参数是 动态参数 或 静态属性
      this.getAttributes()
    },
    // 获取参数的列表数据
    async getAttributes() {
      const len = this.selectedCategoriseKeys.length
      if (len !== 3) {
        this.selectedCategoriseKeys = []
        this.manyTabList = []
        this.onlyTabList = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.categoriesId}/attributes`,
        {
          params: { sel: this.activeTabsName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败')
      }
      // 将attr_vals的字符串形式转数组形式
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        /* 为每个item添加inputVisible和inputValue属性  解决了，数据会串行的问题*/
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeTabsName === 'many') {
        this.manyTabList = res.data
      } else {
        this.onlyTabList = res.data
      }
    },
    // 点击显示修改参数的对话框
    showEditDialog(params) {
      this.editAttributesForm = params
      this.editAttributesVisible = true
    },
    // 删除参数
    async handleDeleteAttributes(params) {
      console.log(params)
      const confirmResult = await this.$confirm(
        `此操作将永久删除该 ${
          this.dialogText + ' ' + params.attr_name
        }, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: ref } = await this.$http.delete(
        `categories/${this.categoriesId}/attributes/${params.attr_id}`
      )
      if (ref.meta.status !== 200)
        return this.$message.error(
          ` ${this.dialogText + ' ' + params.attr_name} 删除失败!`
        )
      this.$message.success(
        ` ${this.dialogText + ' ' + params.attr_name} 删除成功!`
      )
      this.getAttributes()
    },
    // 实现添加参数的对话框
    showAddAttributesDialog() {
      this.addAttributesVisible = true
    },
    // 添加参数
    addAttributes() {
      this.$refs.addAttributesFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.categoriesId}/attributes`,
          {
            attr_name: this.addAttributesForm.attr_name,
            attr_sel: this.activeTabsName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(`添加 ${this.dialogText} 失败`)
        }
        this.$message.success(`添加 ${this.dialogText} 成功`)
        this.addAttributesVisible = false
        this.getAttributes()
      })
    },
    // 编辑参数
    editAttributes() {
      this.$refs.editAttributesFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.categoriesId}/attributes/${this.editAttributesForm.attr_id}`,
          {
            attr_name: this.editAttributesForm.attr_name,
            attr_sel: this.activeTabsName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(`更新 ${this.dialogText} 失败`)
        }
        this.$message.success(`更新 ${this.dialogText} 成功`)
        this.editAttributesVisible = false
        this.getAttributes()
      })
    },
    // 处理输入框完成输入的事件
    async handleInputConfirm(params) {
      if (params.inputValue.trim().length === 0) {
        params.inputVisible = false
        params.inputValue = ''
        return
      }
      params.attr_vals.push(params.inputValue.trim())
      params.inputValue = ''
      params.inputVisible = false
      // 发送网络请求
      this.saveAttrVlas(params)
    },
    // 点击按钮显示输入框
    showInput(params) {
      params.inputVisible = true
      // 让输入框自动获取到焦点
      // $nextTick 方法的作用：就是当页面上元素重新被渲染之后，才会执行指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttrVlas(params) {
      const { data: res } = await this.$http.put(
        `categories/${this.categoriesId}/attributes/${params.attr_id}`,
        {
          attr_name: params.attr_name,
          attr_sel: params.attr_sel,
          attr_vals: params.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(`更新参数项失败`)
      }
      this.$message.success(`更新参数项成功`)
    },
    // 删除对应的参数可选项
    handleClose(index, params) {
      // 删除指定索引的值（splice 方法直接影响原数组）
      params.attr_vals.splice(index, 1)
      // 发送网络请求
      this.saveAttrVlas(params)
    },
  },
  created() {
    this.getCategoriesList()
  },
  computed: {
    isBtnDisabled() {
      return this.selectedCategoriseKeys.length ? false : true
    },
    // 当前选中的三级分类id
    categoriesId() {
      return this.selectedCategoriseKeys.length
        ? this.selectedCategoriseKeys[2]
        : null
    },
    dialogText() {
      return this.activeTabsName === 'many' ? '动态参数' : '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.el-alert,
.btnMargin {
  margin-bottom: 15px;
}

.el-tabs {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  // vertical-align: bottom;
}
</style>